const atob=require('atob')
const jsonp = require('jsonp');
const request = require('request')

let dataURLToFile=(dataURL, filename)=>{
  const arr = dataURL.split(','),
    mime = arr[0].match(/:(.*?);/)[1], //mime类型 image/png
    bstr = atob(arr[1]); //base64 解码

  let n = bstr.length,
    u8arr = new Uint8Array(n);

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }

  return new File([u8arr], filename, {type: mime});
  //return new Blob([a8arr], {type: mime});
}


/**
 * @description 使用jsonp的方法跨域获取在线json
 * @param url url to fetch
 */
let getByJsonp = (url) => {
  return new Promise((resolve,reject) => {
    jsonp(url, {}, (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  })
}
/*
发起http请求,获取在线JSON
 */
let httpRequest = async (url) => {
  const options = {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'  // 需指定这个参数 否则 在特定的环境下 会引起406错误
    }
  }
  return new Promise((resolve, reject) => {
    request.get(url,options, function (err, res, body) {
      if (err) {
        reject(err)
      } else {
        resolve(JSON.parse(body))
      }
    })
  })
}
/*
exif键名替换
 */
let changeKeyName=(obj)=>{

}
/*
拼接图像处理字符串
 */
let handleProcessStr=(obj)=>{

}


module.exports = {
  dataURLToFile,
  getByJsonp,
  httpRequest,
  handleProcessStr
}
